export function uuid(len = 8) {
  const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  const uuid = [];
  let radix = chars.length;
  if (len) {
    radix = Math.min(radix, len);
  }
  for (let i = 0; i < radix; i++) {
    uuid[i] = chars[0 | (Math.random() * radix)];
  }
  return uuid.join("");
}

export const guid = () => {
  const s4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  return s4() + s4() + s4() + s4();
};

export function doubleHandler(fn, delay) {
  let singleClickTimer;

  function _doubleClickHandler(e) {
    if (singleClickTimer) {
      clearTimeout(singleClickTimer);
      singleClickTimer = null;
      fn(e);
    } else {
      singleClickTimer = setTimeout(() => {
        singleClickTimer = null;
      }, delay);
    }
  }

  const cancelDoubleHandler = () => {
    if (singleClickTimer) {
      clearTimeout(singleClickTimer);
      singleClickTimer = null;
    }
  };

  if (typeof fn !== "function" || typeof delay !== "number" || delay < 0) {
    throw new Error("Invalid input: fn must be a function and delay must be a non-negative number");
  }

  return [_doubleClickHandler, cancelDoubleHandler];
}

export const validValue = (val, min, max) => Math.min(Math.max(val, min), max);

export const roundToGrid = (value, gridSize) => Math.round(value / gridSize) * gridSize;
